package com.asr.testclient.service;

import com.asr.testclient.model.ServerMessage;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON消息解析类
 * 负责解析从ASR服务器接收的JSON消息
 */
public class MessageParser {
    private static final Logger logger = LoggerFactory.getLogger(MessageParser.class);
    private final Gson gson;

    public MessageParser() {
        this.gson = new Gson();
    }

    /**
     * 解析JSON字符串为ServerMessage对象
     * @param json JSON格式的字符串
     * @return ServerMessage对象，如果解析失败返回null
     */
    public ServerMessage parse(String json) {
        if (json == null) {
            logger.error("Received null JSON message");
            return null;
        }

        String trimmedJson = json.trim();
        if (trimmedJson.isEmpty()) {
            logger.error("Received empty JSON message");
            return null;
        }

        try {
            ServerMessage message = gson.fromJson(trimmedJson, ServerMessage.class);
            
            if (message == null) {
                logger.error("Gson returned null for JSON: {}", 
                    trimmedJson.length() > 100 ? trimmedJson.substring(0, 100) + "..." : trimmedJson);
                return null;
            }
            
            if (message.getType() == null || message.getType().isEmpty()) {
                logger.warn("Parsed message has no type field");
            }
            
            logger.debug("Successfully parsed message of type: {}", message.getType());
            return message;
            
        } catch (JsonSyntaxException e) {
            logger.error("JSON syntax error parsing message: {}", 
                trimmedJson.length() > 100 ? trimmedJson.substring(0, 100) + "..." : trimmedJson, e);
            return null;
        } catch (Exception e) {
            logger.error("Unexpected error parsing JSON message", e);
            return null;
        }
    }

    /**
     * 从ServerMessage中提取识别结果文本
     * 支持实时模式(recognition_result)和文件模式(file_recognition_result)
     * @param message ServerMessage对象
     * @return 识别结果文本，如果不存在返回null
     */
    public String extractRecognitionResult(ServerMessage message) {
        if (message == null) {
            logger.error("Cannot extract recognition result from null message");
            return null;
        }

        String messageType = message.getType();
        if (messageType == null) {
            logger.error("Message type is null");
            return null;
        }

        // 支持实时模式和文件模式的识别结果
        if (!"recognition_result".equals(messageType) && !"file_recognition_result".equals(messageType)) {
            logger.warn("Message type is not a recognition result: {}", messageType);
            return null;
        }

        String text = message.getText();
        if (text == null) {
            logger.warn("Recognition result message has null text field");
            return null;
        }

        if (text.trim().isEmpty()) {
            logger.warn("Recognition result message has empty text field");
            return null;
        }

        logger.debug("Extracted recognition result: {}", text);
        return text;
    }

    /**
     * 从ServerMessage中提取错误信息
     * @param message ServerMessage对象
     * @return 错误信息，如果不存在返回null
     */
    public String extractErrorMessage(ServerMessage message) {
        if (message == null) {
            logger.error("Cannot extract error message from null message");
            return null;
        }

        String messageType = message.getType();
        if (messageType == null) {
            logger.error("Message type is null");
            return null;
        }

        if (!"error".equals(messageType)) {
            logger.warn("Message type is not 'error': {}", messageType);
            return null;
        }

        String errorMsg = message.getMessage();
        if (errorMsg == null) {
            logger.warn("Error message has null message field");
            return null;
        }

        if (errorMsg.trim().isEmpty()) {
            logger.warn("Error message has empty message field");
            return null;
        }

        logger.debug("Extracted error message: {}", errorMsg);
        return errorMsg;
    }
}
